package org.s166.ums.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.s166.ums.commons.ResultDto;
import org.s166.ums.dao.UserDao;
import org.s166.ums.dao.impl.UserDaoImpl;
import org.s166.ums.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 用户登录接口
 */
@WebServlet("/login.do")
public class LoginServlet extends BaseServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 从客户端表单中获取数据
        String name = req.getParameter("name") ;
        String pass = req.getParameter("pass") ;

        System.out.println("====>"+name);
        System.out.println("====>"+pass);

        // 业务处理... -- 抽象出一个业务对象

        // 创建DAO对象，实现数据库的操作
        UserDao userDao = new UserDaoImpl() ;
        User user = userDao.queryByLogin(name,pass) ;


        // 响应结果:把结果封装到ResultDto对象，并以json的格式响应
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();

        String json = null ;
        if(user!=null) {
            // 封装结果到ResultDto对象中
            ResultDto resultDto = successJson(user,200,"登录成功") ;
            //日期格式处理
            json = new GsonBuilder().setDateFormat("yyyy-MM-dd").create().toJson(resultDto) ;
        } else {
            ResultDto resultDto = errorJson("错误的帐号或密码") ;
            json = new Gson().toJson(resultDto) ;
        }

        out.println(json);

        out.flush();
        out.close();
    }
}
